import socket
import os
import threading
import time
from audio import AudioTransfer

save_directory = '/root/paraformer/example/'
# 初始化语音识别模块
audio_transfer = AudioTransfer()

def tcp_dog():
    # 设置服务器的IP地址和端口号
    server_address = ('172.17.0.1', 8090)

    # 创建一个TCP/IP socket
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    try:
        # 连接到服务器
        print(f"连接到服务器 {server_address}...")
        client_socket.connect(server_address)

        # 读取待发送的文件
        cs_file_path = '/root/paraformer/example/dog.bin'
        if os.path.exists(cs_file_path):
            while True:
                with open(cs_file_path, 'rb') as cs_file:  # 使用二进制模式读取
                    # print("开始发送文件数据...")
                    while True:
                        # 每次读取固定大小的数据块
                        cs_data = cs_file.read(1024)  # 读取 1024 字节
                        if not cs_data:
                            # print("未检测到目标")
                            break  # 文件读取完毕，退出循环
                        if cs_data:
                            client_socket.sendall(cs_data)  # 发送二进制数据
                            with open('/root/paraformer/example/dog.bin', 'wb') as f:
                                f.write(b"")
                            confirmation = client_socket.recv(1024)
                            print(confirmation)
                            # 发送完一次文件后等待0.1秒

                time.sleep(0.1)

        else:
            print(f"文件 {cs_file_path} 不存在")

    except Exception as e:
        print(f"传输过程中发生错误: {e}")

    finally:
        # 关闭客户端socket
        client_socket.close()
        print("连接已关闭")
def tcp_server():
    # 创建一个TCP/IP socket
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # 绑定服务器的IP地址和端口号
    server_address = ('172.17.0.2', 8816)
    print(f"正在启动服务器，监听地址: {server_address}")
    server_socket.bind(server_address)

    # 监听传入的连接
    server_socket.listen(1)

    file_path = os.path.join(save_directory, 'demo.wav')
    while True:
        print("等待客户端连接...")
        connection, client_address = server_socket.accept()
        try:
            print(f"客户端连接成功，地址: {client_address}")

            # 打开文件用于写入
            with open(file_path, 'wb') as f:
                buffer = b''
                while True:
                    # print("xxx")
                    data = connection.recv(1024)
                    buffer += data
                    # print("len.data", len(data), "len.buffer", len(buffer))

                    if not len(data):
                        # print("close")
                        break

                    # print("len2", len(data))
                f.write(buffer)
                print(len(buffer))

            # 算法处理 3s
            result = audio_transfer.recognize_speech(file_path)
            # 回复算法结果
            bresult = result.encode('utf-8')
            connection.sendall(bresult)  # 回送算法结果给客户端
            # translated_text = audio_transfer.translate_text(result)
            # tokenized_text = audio_transfer.tokenize_text(translated_text)
            # print(result)
            # with open(file_path, 'wb') as f:
            #     f.write(tokenized_text)
        finally:
            # 关闭连接
            connection.close()
def tcp_server1():
    # 创建一个TCP/IP socket
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # 绑定服务器的IP地址和端口号
    server_address = ('172.17.0.2', 8817)
    print(f"正在启动服务器，监听地址: {server_address}")
    server_socket.bind(server_address)

    # 监听传入的连接
    server_socket.listen(1)

    while True:
        print("等待客户端连接...")
        connection, client_address = server_socket.accept()
        try:
            print(f"客户端连接成功，地址: {client_address}")
            data1 = connection.recv(1024).decode('utf-8')
            print(data1)
            translated_text = audio_transfer.translate_text(data1)
            print(translated_text)
            tokenized_text = audio_transfer.tokenize_text(translated_text)
            print(tokenized_text)
            # print(result)
            with open('/root/paraformer/example/input.bin', 'wb') as f:
                f.write(tokenized_text)
        finally:
            # 关闭连接
            connection.close()

if __name__ == "__main__":
    thread1 = threading.Thread(target=tcp_server)
    thread2 = threading.Thread(target=tcp_server1)
    thread3 = threading.Thread(target=tcp_dog)

    # 启动线程
    thread1.start()
    thread2.start()
    thread3.start()

    # 确保主线程等待子线程的结束
    thread1.join()
    thread2.join()
    thread3.join()